package cn.gson.crm.controller.graduation;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.gson.crm.model.dao.LanguageDao;
import cn.gson.crm.model.dao.ResumeDao;
import cn.gson.crm.model.dao.ResumeEvaluateDao;
import cn.gson.crm.model.dao.ResumeExperienceDao;
import cn.gson.crm.model.dao.ResumeProjectDao;
import cn.gson.crm.model.dao.StudentDao;
import cn.gson.crm.model.entity.JyLanguage;
import cn.gson.crm.model.entity.JyResume;
import cn.gson.crm.model.entity.JyResumeEvaluate;
import cn.gson.crm.model.entity.JyResumeExperience;
import cn.gson.crm.model.entity.JyResumeProject;
import cn.gson.crm.model.entity.Student;
import cn.gson.crm.model.mapper.ResumeMapper;
import lombok.extern.log4j.Log4j;

/**
 * 简历Controller
 * 
 * @author asus
 *
 */
@Controller
@RequestMapping("/resumes")
@Log4j
public class ResumeController {
	/**
	 * 简历Dao
	 */
	@Autowired
	private ResumeDao resumeDao;
	/**
	 * 简历工作经历Dao
	 */
	@Autowired
	private ResumeExperienceDao rexDao;
	/**
	 * 简历项目经历Dao
	 */
	@Autowired
	private ResumeProjectDao rpDao;
	/**
	 * 语言Dao
	 */
	@Autowired
	private LanguageDao languageDao;
	/**
	 * 简历评价Dao
	 */
	@Autowired
	private ResumeEvaluateDao resumeevaDao;
	/**
	 * 学生Dao
	 */
	@Autowired
	private StudentDao stuDao;
	/**
	 * 简历Mapper
	 */
	@Autowired
	private ResumeMapper resumeMapper;

	/**
	 * 查询简历信息显示在列表
	 * 
	 * @param resume
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("/resume")
	@ResponseBody
	public Map<String, Object> resume(Student resume, @RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize) {
		// 查询数据
		PageHelper.startPage(pageNum, pageSize);
		List<JyResume> pageData = resumeMapper.resumeList(resume);
		PageInfo<JyResume> info = new PageInfo<>(pageData);
		// 组装返回结果
		Map<String, Object> obj = new HashMap<String, Object>(16);
		obj.put("total", info.getTotal());
		obj.put("rows", info.getList());
		return obj;
	}

	/**
	 * 查询简历信息显示在前台列表
	 * 
	 * @param resume
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("/recommend")
	@ResponseBody
	public Map<String, Object> recommend(String resumeName,
			@RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize) {
		// 查询数据
		PageHelper.startPage(pageNum, pageSize);
		List<Map<String, Object>> pageData = resumeMapper.selectRecommend(resumeName);

		PageInfo<Map<String, Object>> info = new PageInfo<>(pageData);
		// 组装返回结果
		Map<String, Object> obj = new HashMap<String, Object>(16);
		obj.put("total", info.getTotal());
		obj.put("rows", info.getList());
		return obj;
	}

	/**
	 * 传递数据到简历详情页面
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("resume_details/{id}")
	public String resumeDetails(@PathVariable(name = "id", required = false) Long id, Model model) {
		if (id != null) {
			JyResume r = resumeDao.findOne(id);
			List<Map<String, Object>> rp = resumeMapper.selectProject(id);
			List<Map<String, Object>> re = resumeMapper.selectExperience(id);
			List<Map<String, Object>> reva = resumeMapper.selectEvaluate(id);
			Student stu = stuDao.findOne(r.getStudent().getId());
			String age = getAge(r.getBirth());
			for (int i = 0; i < re.size(); i++) {
				String time = getTime(re.get(i).get("start_time").toString(), re.get(i).get("resign").toString());
				re.get(i).put("time", time);
			}
			model.addAttribute("age", age);
			model.addAttribute("resume", r);
			model.addAttribute("rp", rp);
			model.addAttribute("re", re);
			model.addAttribute("stu", stu);
			model.addAttribute("reva", reva);
		}
		return "resume_details";
	}

	/**
	 * 添加简历评价
	 * 
	 * @param re
	 * @param br
	 * @return
	 */
	@PostMapping("/saveresume")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
	public Map<String, Object> saveResume(@Valid JyResumeEvaluate re, BindingResult br) {
		Map<String, Object> obj = new HashMap<String, Object>(16);
		obj.put("success", false);
		System.err.println("+++++:"+re);
		try {
			if (br.hasErrors()) {
				obj.put("message", "校验失败！");
				obj.put("erros", br.getFieldErrors());
			} else {
				if (re.getContent() != null && !"".equals(re.getContent())) {
					resumeevaDao.save(re);
					JyResume jr = resumeDao.findOne(re.getResume().getId());
					jr.setState("已批阅");
					resumeDao.save(jr);
					obj.put("success", true);
					return obj;
				} else {
					obj.put("message", "请输入评价！");
					return obj;
				}
			}
		} catch (Exception e) {
			log.error("添加失败！", e);
			obj.put("message", "添加失败！");
		}
		return obj;
	}

	/**
	 * 打回简历
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("repulse/{id}")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
	public Map<String, Object> guidang(@PathVariable("id") Long id) {
		Map<String, Object> obj = new HashMap<String, Object>(16);
		obj.put("success", false);
		JyResume jy;
		if (id != null && (jy = resumeDao.findOne(id)) != null) {
			resumeMapper.updateRepulse(jy.getId());
			obj.put("success", true);
		} else {
			obj.put("message", "此学员不存在！");
		}
		return obj;
	}

	/**
	 * 查出指定优秀简历的所有信息
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("preview/{id}")
	public String preview(@PathVariable("id") Long id, Model model) {
		if (id != null) {
			JyResume r = resumeDao.findOne(id);
			List<Map<String, Object>> rp = resumeMapper.selectProject(id);
			List<Map<String, Object>> re = resumeMapper.selectExperience(id);
			List<Map<String, Object>> reva = resumeMapper.selectEvaluate(id);
			String age = getAge(r.getBirth());
			for (int i = 0; i < re.size(); i++) {
				String time = getTime(re.get(i).get("start_time").toString(), re.get(i).get("resign").toString());
				re.get(i).put("time", time);
			}
			model.addAttribute("age", age);
			model.addAttribute("resume", r);
			model.addAttribute("rp", rp);
			model.addAttribute("re", re);
			model.addAttribute("reva", reva);
		}
		return "preview";
	}

	/**
	 * 计算年龄
	 * 
	 * @param birthDate
	 * @return
	 */
	public static String getAge(String birthDate) {
		SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");
		String currentTime = myFormat.format(new Date());// 当前时间
		String mydate = birthDate;// 出生日期
		int y = Integer.parseInt(currentTime.substring(0, 4)) - Integer.parseInt(mydate.substring(0, 4));
		int m = Integer.parseInt(currentTime.substring(5, 7)) - Integer.parseInt(mydate.substring(5, 7));
		int d = Integer.parseInt(currentTime.substring(8, 10)) - Integer.parseInt(mydate.substring(8, 10));
		if (m > 0)
			return y + "岁";
		if (m < 0)
			return (y - 1) + "岁";
		if (d > 0)
			return (y + 1) + "岁";
		return y + "岁";
	}

	/**
	 * 计算时间长度
	 * 
	 * @param birthDate
	 * @return
	 */
	public static String getTime(String startTime, String endTime) {
		int y = Integer.parseInt(endTime.substring(0, 4)) - Integer.parseInt(startTime.substring(0, 4));
		int m = 0;
		if (Integer.parseInt(startTime.substring(5, 7)) > Integer.parseInt(endTime.substring(5, 7))) {
			y = y - 1;
			m = 0 - (Integer.parseInt(endTime.substring(5, 7)) - Integer.parseInt(startTime.substring(5, 7)));
			return y + "年" + m + "个月";
		} else if (Integer.parseInt(endTime.substring(5, 7)) > Integer.parseInt(startTime.substring(5, 7))) {
			m = Integer.parseInt(endTime.substring(5, 7)) - Integer.parseInt(startTime.substring(5, 7));
			return y + "年" + m + "个月";
		} else {
			return y + "年";
		}
	}

	/**
	 * 查出所有语言
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("language")
	@ResponseBody
	public Iterable<JyLanguage> language() {
		Iterable<JyLanguage> l = languageDao.findAll();
		return l;
	}

	/**
	 * 查出登录学员的简历
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("/mineresume/{id}")
	public String mineresume(@PathVariable("id") Long id, Model model) {
		List<Map<String, Object>> r = resumeMapper.selectMineResume(id);
		for (int i = 0; i < r.size(); i++) {
			String age = getAge(r.get(i).get("birth").toString());
			r.get(i).put("age", age);
		}
		List<Map<String, Object>> rp = new ArrayList<>();
		List<Map<String, Object>> re = new ArrayList<>();
		List<Map<String, Object>> re1 = new ArrayList<>();
		List<Map<String, Object>> rp1 = new ArrayList<>();
		for (Map<String, Object> map : r) {
			re= resumeMapper.selectExperience(Long.valueOf(map.get("tb_resume_id").toString()));
			for (Map<String, Object> rem : re) {
				re1.add(rem);
			}
			rp=resumeMapper.selectProject(Long.valueOf(map.get("tb_resume_id").toString()));
			for (Map<String, Object> rpm : rp) {
				rp1.add(rpm);
			}
		}
		model.addAttribute("rp", rp1);
		model.addAttribute("re", re1);
		model.addAttribute("r", r);
		return "recep_resume";
	}

	/**
	 * 跳转添加、编辑简历界面
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping({ "editresume/{userid}", "editresume/{userid}/{id}" })
	public String editresume(@PathVariable("userid") Long user, @PathVariable(name = "id", required = false) Long id,
			Model model) {
		if (id != null) {
			JyResume jr = resumeDao.findOne(id);
			if (jr != null) {
				model.addAttribute("jr", jr);
			}
		}
		Integer count = resumeMapper.selectResumeCount(user);
		model.addAttribute("count", count);
		return "edit_resume";
	}
	/**
	 * 添加、编辑简历
	 * @param jr
	 * @param br
	 * @return
	 */
	@RequestMapping("addmineresume")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
	public Map<String, Object> addResume(@Valid JyResume jr, BindingResult br) {
		Map<String, Object> obj = new HashMap<>(16);
		obj.put("success", false);
		if (br.hasErrors()) {
			obj.put("message", "校验失败！");
			obj.put("erros", br.getFieldErrors());
		} else {
			if (jr.getId() == null) {
				jr.setRecommend(false);
				jr.setState("未批阅");
			}else {
				JyResume j = resumeDao.findOne(jr.getId());
				jr.setRecommend(j.getRecommend());
				if("已打回".equals(j.getState())) {
					jr.setState("未批阅");
				}else {
					jr.setState(j.getState());
				}
				
			}
			String age = getAge(jr.getBirth());
			int age1 = Integer.parseInt(age.substring(0, age.length()-1));
			if(age1 < 18 || age1> 60) {
				obj.put("message", "年龄不能低于18岁,也不能大于60岁！注意你的出生日期！");
				return obj;
			}
			jr.setDelete(true);
			resumeDao.save(jr);
			obj.put("success", true);
		}
		return obj;
	}
	/**
	 * 跳转添加、编辑工作经验界面
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping({ "getworks/{resumeid}", "getworks/{resumeid}/{id}" })
	public String getworks(@PathVariable("resumeid") Long resumeid,
			@PathVariable(name = "id", required = false) Long id,
			Model model) {
		if (id != null) {
			JyResumeExperience je = rexDao.findOne(id);
			if (je != null) {
				model.addAttribute("je", je);
			}
		}
		model.addAttribute("resumeid", resumeid);
		return "takework";
	}
	
	/**
	 * 添加、编辑工作经验
	 * @param jr
	 * @param br
	 * @return
	 */
	@RequestMapping("addworks")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
	public Map<String, Object> addwork(@Valid JyResumeExperience je, BindingResult br) {
		Map<String, Object> obj = new HashMap<>(16);
		obj.put("success", false);
		if (br.hasErrors()) {
			obj.put("message", "校验失败！");
			obj.put("erros", br.getFieldErrors());
		} else {
			int y = Integer.parseInt(je.getStartTime().substring(0, 4));
			int y1 = Integer.parseInt(je.getResign().substring(0, 4));
			int m = Integer.parseInt(je.getStartTime().substring(5, 7));
			int m1 = Integer.parseInt(je.getResign().substring(5, 7));
			int d = Integer.parseInt(je.getStartTime().substring(8, 10));
			int d1 = Integer.parseInt(je.getResign().substring(8, 10));
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String newdate = sdf.format(new Date());
			int y2 = Integer.parseInt(newdate.substring(0, 4));
			int m2 = Integer.parseInt(newdate.substring(5, 7));
			int d2 = Integer.parseInt(newdate.substring(8, 10));
			if(y > y1 || (y==y1 && m > m1) || (y==y1 && m==m1 && d>d1)) {
				obj.put("message", "入职时间不能早于辞职时间！");
				return obj;
			}else if(y==y1 && (m1-m) < 1) {
				obj.put("message", "入职时间和辞职时间之间必须要1个月以上！");
				return obj;
			}else if(y > y2 ||  (y==y2 && m > m2) || (y==y2 && m==m2 && d>d2)){
				obj.put("message", "入职时间不能早于当前时间！");
				return obj;
			}else if(y1 > y2 ||  (y1==y2 && m1 > m2) || (y1==y2 && m1==m2 && d1>d2)){
				obj.put("message", "辞职时间不能早于当前时间！");
				return obj;
			}
			if(je.getId() != null && "已打回".equals(je.getResume().getState())) {
				je.getResume().setState("未批阅");
			}
			je.setDelete(true);
			rexDao.save(je);
			obj.put("success", true);
		}
		return obj;
	}
	
	/**
	 * 跳转添加、编辑项目经验界面
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping({ "getprojects/{resumeid}", "getprojects/{resumeid}/{id}" })
	public String getProject(@PathVariable("resumeid") Long resumeid,
			@PathVariable(name = "id", required = false) Long id,
			Model model) {
		if (id != null) {
			JyResumeProject jp = rpDao.findOne(id);
			if (jp != null) {
				model.addAttribute("jp", jp);
			}
		}
		model.addAttribute("resumeid", resumeid);
		return "takeproject";
	}
	/**
	 * 添加、编辑项目经验
	 * @param jp
	 * @param br
	 * @return
	 */
	@RequestMapping("addprojects")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
	public Map<String, Object> addprojects(@Valid JyResumeProject jp, BindingResult br) {
		Map<String, Object> obj = new HashMap<>(16);
		obj.put("success", false);
		if (br.hasErrors()) {
			obj.put("message", "校验失败！");
			obj.put("erros", br.getFieldErrors());
		} else {
			int y = Integer.parseInt(jp.getStartTime().substring(0, 4));
			int y1 = Integer.parseInt(jp.getEndTime().substring(0, 4));
			int m = Integer.parseInt(jp.getStartTime().substring(5, 7));
			int m1 = Integer.parseInt(jp.getEndTime().substring(5, 7));
			int d = Integer.parseInt(jp.getStartTime().substring(8, 10));
			int d1 = Integer.parseInt(jp.getEndTime().substring(8, 10));
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String newdate = sdf.format(new Date());
			int y2 = Integer.parseInt(newdate.substring(0, 4));
			int m2 = Integer.parseInt(newdate.substring(5, 7));
			int d2 = Integer.parseInt(newdate.substring(8, 10));
			if(y > y1 || (y==y1 && m > m1) || (y==y1 && m==m1 && d>d1)) {
				obj.put("message", "开始时间不能早于结束时间！");
				return obj;
			}else if(y==y1 && m==m1 && d==d1) {
				obj.put("message", "开始时间和结束时间不能相同！");
				return obj;
			}else if(y > y2 ||  (y==y2 && m > m2) || (y==y2 && m==m2 && d>d2)){
				obj.put("message", "开始时间不能早于当前时间！");
				return obj;
			}else if(y1 > y2 ||  (y1==y2 && m1 > m2) || (y1==y2 && m1==m2 && d1>d2)){
				obj.put("message", "结束时间不能早于当前时间！");
				return obj;
			}
			if(jp.getId() != null && "已打回".equals(jp.getResume().getState())) {
				jp.getResume().setState("未批阅");
			}
			jp.setDelete(true);
			rpDao.save(jp);
			obj.put("success", true);
		}
		return obj;
	}
	/**
	 * 删除整个简历(虚拟删除)
	 * @param id
	 * @return
	 */
	@GetMapping("deleteresume/{id}")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
	public Map<String, Object> deleteresume(@PathVariable("id") Long id) {
		Map<String, Object> obj = new HashMap<String, Object>(16);
		obj.put("success", false);
		if (id != null && resumeDao.findOne(id) != null) {
			resumeMapper.deleteProjects(id);
			resumeMapper.deleteExperience(id);
			resumeMapper.deleteResume(id);
			obj.put("success", true);
		} else {
			obj.put("message", "此简历不存在！");
		}
		return obj;
	} 
	
	/**
	 * 删除简历工作经验(虚拟删除)
	 * @param id
	 * @return
	 */
	@GetMapping("deletework/{id}")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
	public Map<String, Object> deletework(@PathVariable("id") Long id) {
		Map<String, Object> obj = new HashMap<String, Object>(16);
		obj.put("success", false);
		if (id != null && rexDao.findOne(id) != null) {
			resumeMapper.deleteWork(id);
			obj.put("success", true);
		} else {
			obj.put("message", "此记录不存在！");
		}
		return obj;
	} 
	/**
	 * 删除简历项目经验(虚拟删除)
	 * @param id
	 * @return
	 */
	@GetMapping("deleteproject/{id}")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
	public Map<String, Object> deleteproject(@PathVariable("id") Long id) {
		Map<String, Object> obj = new HashMap<String, Object>(16);
		obj.put("success", false);
		if (id != null && rpDao.findOne(id) != null) {
			resumeMapper.deleteProject(id);
			obj.put("success", true);
		} else {
			obj.put("message", "此记录不存在！");
		}
		return obj;
	} 
	/**
	 * 公司下拉框
	 * @param id
	 * @return
	 */
	@RequestMapping("company/{experienceId}")
	@ResponseBody
	public List<Map<String, Object>> company(@PathVariable("experienceId") Long id) {
		List<Map<String, Object>> re = new ArrayList<>();
		re=resumeMapper.selectExperience(id);
		return re;
	}
	/**
	 * 推荐简历
	 * @param id
	 * @return
	 */
	@GetMapping("getrecom/{id}")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
	public Map<String, Object> getrecom(@PathVariable("id") Long id) {
		Map<String, Object> obj = new HashMap<String, Object>(16);
		obj.put("success", false);
		if (id != null && resumeDao.findOne(id) != null) {
			resumeMapper.getRecom(id);
			obj.put("success", true);
		} else {
			obj.put("message", "此记录不存在！");
		}
		return obj;
	} 
	
	/**
	 * 取消推荐简历
	 * @param id
	 * @return
	 */
	@GetMapping("outrecom/{id}")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
	public Map<String, Object> outrecom(@PathVariable("id") Long id) {
		Map<String, Object> obj = new HashMap<String, Object>(16);
		obj.put("success", false);
		if (id != null && resumeDao.findOne(id) != null) {
			resumeMapper.outRecom(id);
			obj.put("success", true);
		} else {
			obj.put("message", "此记录不存在！");
		}
		return obj;
	} 
}
